package com.xpgk.sbwx.binShopService;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Before;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.sun.xml.internal.bind.v2.runtime.reflect.opt.FieldAccessor_Float;
import com.xpgk.dto.RenderBean;
import com.xpgk.mvc.base.BaseController;
import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.mvc.bentryRegister.CustomerAgreement;
import com.xpgk.mvc.bentryRegister.CustomerDetail;
import com.xpgk.mvc.bentryRegister.CustomerHabit;
import com.xpgk.mvc.bentryRegister.CustomerProduct;
import com.xpgk.mvc.binShopService.BinShopServiceService;
import com.xpgk.mvc.binShopService.CustomerService;
import com.xpgk.mvc.binShopService.CustomerServiceMonthNurse;
import com.xpgk.mvc.binShopService.CustomerServiceNurse;
import com.xpgk.mvc.binShopService.ServicePartSize;
import com.xpgk.mvc.codeSet.Code;
import com.xpgk.mvc.organization.Organization;
import com.xpgk.mvc.productSales.ProductSalesOrder;
import com.xpgk.mvc.productSet.Product;
import com.xpgk.mvc.statistic.dailyTotalStatistic.DailyNursingTotal;
import com.xpgk.mvc.statistic.monthTotalStatistic.MonthTotal;
import com.xpgk.mvc.statistic.yearTotalStatistic.YearTotal;
import com.xpgk.mvc.user.User;
import com.xpgk.tools.ToolDateTime;

public class WXBinShopServiceController extends BaseController {
	@SuppressWarnings("unused")
	private static final Log log = Log.getLog(WXBinShopServiceController.class);

	private BinShopServiceService binShopServiceService;

	public void index() {
		
		render("/sbwx/weight.jsp");
	}

	/**
	 * 获取顾客是否支付疗程款，单疗程次数，测量尺寸日期
	 * 
	 */
	public void getInshopInfo() {
		RenderBean result = new RenderBean();
		String customerIds = getPara("customerIds");
		Customer cus = Customer.dao.findById(customerIds);
		// cus 是否购买产品，和疗程
		StringBuffer sb = new StringBuffer();
		sb.append("亲，");
		String sql1 = " SELECT * FROM sb_customer_product WHERE customerID = ?   AND  ( productID IN ('0896ce4d4970455d9184e6dd1ced6a0e','27aeb2d41d044394b9b58f6814baa4fa','4777c2c215b6408ab13c1eac4190ce46'))  ";
		List<Record> cdl = Db.find(sql1, customerIds);
		if (cdl == null || cdl.size() == 0) {
			result.getMap().put("msg",sb.append("没有购买疗程！"));
		}

		String sql0 = " SELECT * FROM sb_customer_product WHERE customerID = ?   AND  ( productID IN ('daaba791f4104ae98504a1bc421e0d8d','95e2ae17462e4d0eb1dc84bc63bc478a'))  ";
		cdl = Db.find(sql0, customerIds);
		if (cdl == null || cdl.size() == 0) {
			result.getMap().put("msg",sb.append("没有购买瘦身产品！"));
		} else {

			String sql01 = "SELECT  SUM(totalExperience)<5  sy FROM sb_customer_product WHERE      productID ='daaba791f4104ae98504a1bc421e0d8d'  and customerID = ?";
			cdl = Db.find(sql01, customerIds);
			if (cdl == null || cdl.size() == 0) {
				if (Integer.parseInt(cdl.get(0).getStr("sy")) > 0) {
					result.getMap().put("msg", sb.append("紧肤膏剩余" + cdl.get(0).getStr("sy") + "次！"));
				}
			}

			String sql02 = " SELECT  SUM(totalExperience)<5  sy FROM sb_customer_product WHERE      productID ='95e2ae17462e4d0eb1dc84bc63bc478a'  and customerID = ?";
			cdl = Db.find(sql01, customerIds);
			if (cdl == null || cdl.size() == 0) {
				if (Integer.parseInt(cdl.get(0).getStr("sy")) > 0) {
					result.getMap().put("msg", sb.append("精油剩余" + cdl.get(0).getStr("sy") + "次！"));
				}
			}
		}
		if(sb.toString().length()>5){
			result.getMap().put("msg",sb.toString());
		}
		
		
		
		
		String sql033 = " SELECT * FROM (SELECT weight-lastWeight  tz from sb_customer_service WHERE customerID = ? and dataStatus in ('1','2') ORDER BY startTime DESC  LIMIT 0,1 ) a WHERE a.tz >0";
		cdl = Db.find(sql033, customerIds);
		if (cdl != null &&cdl.size() == 1 ) {
			
			 result.getMap().put("zcscount",1);
			 result.getMap().put("zcs","亲，您连续涨称"+1+"次！");
			 String sql032 = " SELECT * FROM (SELECT weight-lastWeight  tz from sb_customer_service WHERE customerID = ? and dataStatus in ('1','2') ORDER BY startTime DESC  LIMIT 0,2 ) a WHERE a.tz >0";
				cdl = Db.find(sql032, customerIds);
				if (cdl != null && cdl.size() == 2 ) {
					 result.getMap().put("zcscount",2);
					 result.getMap().put("zcs","亲，您连续涨称"+2+"次！");
					 String sql031 = " SELECT * FROM (SELECT weight-lastWeight  tz from sb_customer_service WHERE customerID = ? and dataStatus in ('1','2') ORDER BY startTime DESC  LIMIT 0,3 ) a WHERE a.tz >0";
						cdl = Db.find(sql031, customerIds);
						if (cdl != null && cdl.size() == 3 ) {
							 result.getMap().put("zcscount",3);
							 result.getMap().put("zcs","亲，您连续涨称"+3+"次！");
						}
				}
		}
		
		
		

		String sql2 = " select  *  from sb_customer_detail   where customerIds= ?  and dataStatus in ('1','2')";
		cdl = Db.find(sql2, customerIds);
		Record cd = cdl.get(0);// CustomerDetail

		Date startDate = cd.getDate(CustomerDetail.column_firstDate);
		if (startDate != null) {
			Date endDate = new Date();

			Calendar startCalendar = Calendar.getInstance();
			Calendar endCalendar = Calendar.getInstance();

			startCalendar.setTime(startDate);
			endCalendar.setTime(endDate);

			int day = endCalendar.get(Calendar.DAY_OF_MONTH) - startCalendar.get(Calendar.DAY_OF_MONTH);
			int month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
			int year = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);

			if (day < 0) {
				month--;
			}

			if (month < 0) {
				month += 12;
				year--;
			}
			if (year >= 2) {
				result.getMap().put("yearflag", "0");
				result.getMap().put("yearms",
						"亲，您首次到店日期为"
								+ new SimpleDateFormat("yyyy-MM-dd").format(cd.getDate(CustomerDetail.column_firstDate))
								+ "已经：" + year + "年" + month + "个月不可服务!");
			}
		}
		if (cd.getStr(CustomerDetail.column_customerType) != null	&& cd.getStr(CustomerDetail.column_customerType) .equals("2")) {
				result.getMap().put("weightflag", "0");
				result.getMap().put("weightms","亲，您已经成为巩固顾客，恭喜您减肥成功！");
		}

		String sql = "SELECT  ifnull(sum(arrears),0)  qkje  from   sb_product_sales_order   where  customerIds=?    and  arrears>0";
		List<ProductSalesOrder> psoList = ProductSalesOrder.dao.find(sql, customerIds);
		Double qkje = psoList.get(0).getDouble("qkje");

		if (qkje != null && qkje > 0) {
			result.getMap().put("qkjeflag", "0");
			result.getMap().put("qkjems", "亲，您有欠款未还，金额为" + qkje.toString() + "元");
		}

		// 是否支付疗程款
		String isPay = cus.getCustomerAgreement().getStr(CustomerAgreement.column_isPay);
		result.getMap().put("isPay", isPay);
		// 是否是单疗程，单疗程剩余次数
		String lcsql = getSqlMy(CustomerProduct.sqlId_selByCusAndType);
		CustomerProduct lccp = CustomerProduct.dao.findFirst(lcsql, cus.getStr(CustomerProduct.column_ids), Code.lc_ids,
				getCUserOrganIds());
		if (lccp != null && lccp.getStr("proUnits").equals(Code.dlc_units)) {
			result.getMap().put("dlcnum", lccp.getFloat("totalexperience"));
		}
		// 查询测量尺寸时间
		String sizesql = getSqlMy(ServicePartSize.sqlId_selLastSize);
		ServicePartSize sps = ServicePartSize.dao.findFirst(sizesql, customerIds, new Date());
		if (sps != null) {
			int days = ToolDateTime.getDateDaySpace(sps.getTimestamp(ServicePartSize.column_createDate), new Date());
			if (days >= 15) {
				result.getMap().put("measureSizeDay", "1");
			}
		} else {
			int days = ToolDateTime.getDateDaySpace(cus.getTimestamp(Customer.column_registtime), new Date());
			if (days >= 15) {
				result.getMap().put("measureSizeDay", "1");
			}
		}
		SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> queryParam = new HashMap<String, Object>();
		queryParam.put("customerIds", customerIds);
		queryParam.put("datestr",sdf.format(new Date()));
		List<Record> rs = binShopServiceService.find(CustomerService.sqlId_targetWei, queryParam);
		
		// 查询目标
		if (rs != null && rs.size() > 0) {
			for (Record record : rs) {
				record.set("startTime", sdf.format(record.getDate("startTime")));
				record.set("endTime", sdf.format(record.getDate("endTime")));
			}
			
			result.getMap().put("mbRecord", rs);
		}
		renderJson(result.getMap());
	}

	/**
	 * 查出会员拥有的服务类的产品
	 */
	public void getPartProduct() {
		String customerIds = getPara("customerIds");
		String sql = getSqlMy(CustomerProduct.sqlId_selByCusAndUseIds);
		List<CustomerProduct> cpList = CustomerProduct.dao.find(sql, customerIds, Code.cpytFw_ids);
		renderJson(cpList);
	}

	/**
	 * 获取服务部位产品使用经验值
	 * 
	 */
	public void getPartInfo() {
		String curUserIds = getCUserIds();
		String customerIds = getPara("customerIds");
		List<Map> js = binShopServiceService.getPartInfo(customerIds, curUserIds);
		renderJson(js);
	}

	/**
	 * 获取测量部位尺寸信息
	 * 
	 */
	public void getPartSizeInfo() {
		String customerIds = getPara("customerIds");
		List<Map> js = binShopServiceService.getPartSizeInfo(customerIds);
		renderJson(js);
	}

	/**
	 * 获取服务人员下拉框
	 * 
	 */
	public void getServicesUser() {
		// 获取当前登录机构id
		String cudid = getCUserOrganIds();
		String userSql = getSqlMy(User.sqlId_organUserList);
		List<User> uList = User.dao.find(userSql, cudid);
		renderJson(uList);
	}

	/**
	 * 根据顾客id查出生活习惯
	 * 
	 */
	public void getCusHabit() {
		String customerIds = getPara("customerIds");
		// 获取当前登录机构id
		String cudid = getCUserOrganIds();
		CustomerHabit ch = binShopServiceService.getCusHabit(customerIds, cudid);
		setAttr("customerHabit", ch);
		render("dailyLife.html");
	}

	/**
	 * 保存服务和生活习惯
	 * 
	 */
	@Before(Tx.class)
	public void saveInfo() {
		String openid = getPara("openid");
		String organids = getPara("organids");
		String yzm = getPara("yzm");
		Organization org = Organization.dao.findById(organids);
		if(org!=null && org.getStr(Organization.column_todayyzm)!=null && org.getStr(Organization.column_todayyzm).equals(yzm)){
			
		
		Customer customer = Customer.dao.findFirst("SELECT * FROM sb_customer WHERE dataStatus in ('1','2') and openid = ? and organIds = ?",openid,organids);
		if(customer!=null){
			
		
		String customerIds = customer.getStr(Customer.column_ids);

		CustomerDetail cdet = CustomerDetail.dao.findFirst(" SELECT * FROM sb_customer_detail WHERE customerIds = ? and dataStatus in ('1','2') ",
				customerIds);
		boolean isXgk = ToolDateTime.format(cdet.getDate(CustomerDetail.column_firstDate), ToolDateTime.pattern_y).equals(ToolDateTime.format(new Date(), ToolDateTime.pattern_y));
		boolean isdndyXgk = ToolDateTime.format(cdet.getDate(CustomerDetail.column_firstDate), ToolDateTime.pattern_ym).equals(ToolDateTime.format(new Date(), ToolDateTime.pattern_ym));
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String datestr = sdf.format(new Date());
		CustomerService csm = CustomerService.dao.findFirst(" SELECT ids FROM sb_customer_service WHERE customerID = ? and  DATE_FORMAT(startTime,'%Y-%m-%d')  = ? and dataStatus in ('1','2')   LIMIT 1",customerIds, datestr);
		boolean  isdb = false;//本次是否达标
		boolean  hasdb = false;//是否已为达标用户
		if (csm == null) {
			String nowweight = getPara("nowweight");
			// 获取当前登录机构id
			String cudid = organids;
			// 获取当前登陆人员id
			String userid = customerIds;
			CustomerService cs = new CustomerService();
			cs.set(CustomerService.column_customerID, customerIds)
			  .set(CustomerService.column_startTime, new Date())
			  .set(CustomerService.column_createDate, new Date())
			  .set(CustomerService.column_createId, userid)
			  .set(CustomerService.column_isgk, 1);//顾客自己添加的数据
			
			binShopServiceService.saveTotalInfo(customerIds,cudid,isXgk);//保存到店人数，服务人数，服务次数
			if (StringUtils.isNotBlank(nowweight)) {
				cs.set(CustomerService.column_weight, Float.parseFloat(nowweight));
				CustomerService csm1 = CustomerService.dao.findFirst(
						" SELECT weight FROM sb_customer_service WHERE customerID = ? and dataStatus in ('1','2')  ORDER BY endTime DESC  LIMIT 1",
						customerIds);
				if (csm1 == null) {
					cs.set(CustomerService.column_lastWeight, cdet.getFloat(CustomerDetail.column_firstWeight));
				} else {
					cs.set(CustomerService.column_lastWeight, csm1.getFloat("weight"));
				}
				
				binShopServiceService.saveServiceInfo(cdet,cs,customerIds,cudid,userid,isXgk);
				if(cdet != null )
				{	//1：塑性，0减肥，2：巩固
					
					
					if(cdet.getStr(CustomerDetail.column_customerType) != null  && cdet.getStr(CustomerDetail.column_customerType).equals("2")){
						cs.set(CustomerService.column_isGg,"1");//0减肥，1巩固，2塑形
						hasdb = true;
					}else if( cdet.getStr(CustomerDetail.column_customerType) != null  && cdet.getStr(CustomerDetail.column_customerType).equals("1")){
						cs.set(CustomerService.column_isGg,"2");//塑形顾客
					}else{
						log.info(customerIds+"现在体重：btbtbtbtbtbtbtbtbt"+"-------------------"+Float.parseFloat(nowweight) +"标体-------------------"+Float.parseFloat(cdet.getStr(CustomerDetail.column_standardWeight))
						+"差值是：--------------"+(Float.parseFloat(nowweight) - Float.parseFloat(cdet.getStr(CustomerDetail.column_standardWeight))));
						if (Float.parseFloat(nowweight) - Float.parseFloat(cdet.getStr(CustomerDetail.column_standardWeight)) <= 0) {
							isdb = true;
								cdet.set(CustomerDetail.column_customerType, "2");
								cs.set(CustomerService.column_isGg, "1");
						}else
						{
							cdet.set(CustomerDetail.column_customerType, "0");
							cs.set(CustomerService.column_isGg, "0");
						}
						cdet.update();
					}
				}
				
				
				CustomerServiceNurse csmn = CustomerServiceNurse.dao.findFirst(" SELECT * FROM sb_customer_service_nurse WHERE customerID = ? and  YearMon = ?   LIMIT 1",customerIds, datestr.substring(0, 7));
				binShopServiceService.saveOrUpdateNurse(csmn,cs,cdet,1,isdndyXgk);
				CustomerServiceMonthNurse monthNurse = CustomerServiceMonthNurse.dao.findFirst("select * from sb_customer_service_month_nurse where customerIds = ? and organIds = ? and `year` = ? and dataStatus in ('1','2')",customerIds,organids,datestr.substring(0,4));
				binShopServiceService.saveOrUpdateMonthNurse(monthNurse,cs,cdet,1,userid,1);
				
				DailyNursingTotal  dnt = DailyNursingTotal.dao.getDnt(cudid,new Date());
				
				if(dnt != null)
				{
					if(isdb && !hasdb)
					{
						dnt.set(DailyNursingTotal.column_dbrs, dnt.getInt(DailyNursingTotal.column_dbrs)+1);
					}
					double  dcbl =  0d;
					double  rjdc =  0d;
					double  dcjs =  0d;
					double  zcjs =  0d;
					if(dnt.getInt(DailyNursingTotal.column_sddrs)-dnt.getInt(DailyNursingTotal.column_ggrs)>0)
					{
						dcbl = ((double)dnt.getInt(DailyNursingTotal.column_dcrs))/((double)(dnt.getInt(DailyNursingTotal.column_sddrs)-dnt.getInt(DailyNursingTotal.column_ggrs)));
						if(dnt.getDouble(DailyNursingTotal.column_dcjs)!=null){
							dcjs = dnt.getDouble(DailyNursingTotal.column_dcjs);
						}
						if(dnt.getDouble(DailyNursingTotal.column_zcjs)!=null){
							zcjs = dnt.getDouble(DailyNursingTotal.column_zcjs);
						}
						rjdc = ((double)(dcjs-zcjs))/((double)(dnt.getInt(DailyNursingTotal.column_sddrs)-dnt.getInt(DailyNursingTotal.column_ggrs)));
					}
					dnt.set(DailyNursingTotal.column_dcrszb,new DecimalFormat("#.00").format(dcbl*100))
					.set(DailyNursingTotal.column_rjdc,new DecimalFormat("#.00").format(rjdc));
					
					if (!dnt.update()) {
						log.debug("更新日综合查询表失败");
						throw new RuntimeException("更新日综合查询表失败!");
					}
				}
				
			}
			cs.set(CustomerService.column_organids, cudid);
			cs.set(CustomerService.column_dataStatus, "1");
			
			boolean flag = cs.save();
			if (StringUtils.isNotBlank(nowweight)) {
				String lcsql = getSqlMy(CustomerProduct.sqlId_selByCusAndType);
				CustomerProduct lccp = CustomerProduct.dao.findFirst(lcsql, customerIds, Code.lc_ids,
						organids);
				if (lccp != null && lccp.getStr("proUnits").equals(Code.dlc_units)) {
					CustomerProduct dlccp = CustomerProduct.dao.findById(lccp.getStr("ids"));
					dlccp.set(CustomerProduct.column_totalExperience,
							dlccp.getFloat(CustomerProduct.column_totalExperience) - 1)
							.set(CustomerProduct.column_updateDate, new Date());
					if (!dlccp.update()) {
						log.debug("更新单疗程剩余失败");
						throw new RuntimeException("更新单疗程剩余失败!");
					}
				}
				String servicesql = getSqlMy(CustomerService.sqlId_selMinByCus);
				List<CustomerService> csList1 = CustomerService.dao.find(servicesql, customerIds);
				if (csList1 != null && csList1.size() > 0) {
					CustomerService cs1 = csList1.get(0);
					cdet.set(CustomerDetail.column_minDate, cs1.getDate(CustomerService.column_createDate));
					cdet.set(CustomerDetail.column_minWeight, cs1.getFloat(CustomerService.column_weight));
					cdet.set(CustomerDetail.column_updateDate, new Date());
					cdet.set(CustomerDetail.column_updateId, cudid);
				}
				cdet.set(CustomerDetail.column_toStoreDate, new Date());
				cdet.set(CustomerDetail.column_nowWeight, nowweight);
				cdet.update();
			}
			
			if (flag) {
				renderText("200");
			} else {
				renderText("服务异常");
			}
			
		} else {
			renderText("亲，今天已经结束服务了，明天再来!");
		}
		}else{
			renderText("亲，请先去顾客绑定绑定手机号!");
		}
		}else{
			renderText("验证码错误");
		}

	}

	

	/**
	 * 获取顾客减重目标
	 * 
	 */
	public void getDelweight() {
		String customerIds = getPara("customerIds");
		String date = getPara("date");
		String orgids = getCUserOrganIds();
		Map<String, Object> mm = binShopServiceService.getDelweight(customerIds, date, orgids);
		renderJson(mm);
	}

	/**
	 * 获取顾客减重记录
	 * 
	 * @throws ParseException
	 * 
	 */
	public void getDelweiRecord() throws ParseException {
		String customerIds = getPara("customerIds");
		String date = getPara("date");
		String orgids = getCUserOrganIds();
		List<CustomerService> csLsit = binShopServiceService.getDelweiRecord(orgids, customerIds, date);
		renderJson(csLsit);
	}

	
	
	/**
	 * 体重登记
	 * 
	 */
	public void getByOpenid() {
		String openid = getPara("openid");
		String organids = getPara("organids");
		Customer customer = Customer.dao.findFirst("SELECT * FROM sb_customer WHERE dataStatus in ('1','2') and openid = ? and organIds = ?",openid,organids);
		CustomerDetail cdet =new CustomerDetail();
		if(customer!=null){
			String sql = "SELECT * FROM sb_customer_detail WHERE customerIds = ? AND dataStatus in ('1','2')";
			cdet = CustomerDetail.dao.findFirst(sql,customer.getStr(Customer.column_ids));
			
		}
		renderJson(cdet);
	}
}
